<?php

class UrlruleAction extends PublicAction {

    protected $db;

    function _initialize() {
        parent::_initialize();
        $this->db = D('admin/urlrule');
    }

    public function index()
    {
        $name = MODULE_NAME;
        $model = M($name);
        if(empty($_REQUEST['where'])){
            $list = $model->select();
        }else{
            $list = $model->where($_REQUEST['where'])->select();
        }

        $this->assign('list', $list);
        $this->display();
    }

    function update()
    {

        if($_POST['setup'])
            $_POST['setup'] = array2string($_POST['setup']);

        $name = MODULE_NAME;
        $model = D( $name );

        if (false === $model->create()) {
          $this->error($model->getError ());
        }

        if (false !== $model->save ()) {

          if(in_array(ucfirst($name),$this->cache_model))
            savecache($name);

          if($_POST['aid']){
            $Attachment =M('attachment');
            $aids =  implode(',',$_POST['aid']);
            $data['id'] = $_POST['id'];
            $data['catid'] = intval($_POST['catid']);
            $data['status'] = '1';
            $Attachment->where("aid in (".$aids.")")->save($data);
          }

          if($_POST['isajax'])
            $this->assign('dialog','1');

          $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(MODULE_NAME.'/index');

          $this->assign('jumpUrl', $jumpUrl);
          $this->success(L('edit_ok'));
        } else {
            $this->success (L('edit_error').': '.$model->getDbError());
        }
    }

    function add()
    {
        $name = MODULE_NAME;
        $this->display('edit');
    }
    function edit()
    {

        $name = MODULE_NAME;
        $model = M($name);
        $pk = ucfirst($model->getPk());
        $id = $_REQUEST[$model->getPk()];

        if(empty($id))
            $this->error(L('do_empty'));

        $do = 'getBy'.$pk;
        $vo = $model->$do( $id );

        if($vo['setup'])
            $vo['setup'] = string2array($vo['setup']);

        $this->assign('vo', $vo);
        $this->display();
    }
}